package com.github.jspxnet.worktask.core.node;

import com.github.jspxnet.json.JSONObject;
import com.github.jspxnet.utils.BeanUtil;
import com.github.jspxnet.utils.ObjectUtil;
import com.github.jspxnet.worktask.model.dto.ProcessResponse;
import com.github.jspxnet.worktask.model.enums.FlowNodeEnumType;
import com.github.jspxnet.worktask.model.enums.JobEnumType;
import com.github.jspxnet.worktask.model.enums.WorkTaskEnumType;
import com.github.jspxnet.worktask.table.ConfFlowNode;
import com.github.jspxnet.worktask.table.WorkTask;
import com.github.jspxnet.worktask.util.WorkFlowUtil;
import java.util.Date;
import java.util.List;

public class StartNodeAction extends BaseNodeAction {

    @Override
    public ProcessResponse<?> execute() {
        //先放入第一个节点
        //流程发起人信息begin
        try {
            currentWorkTask = BeanUtil.copy(currentConfFlowNode,WorkTask.class);
            currentWorkTask.setNodeId(currentConfFlowNode.getNodeId());
            currentWorkTask.setDocumentNo(workTaskParam.getDocumentNo());
            currentWorkTask.setUsers(workTaskParam.getUsers());
            currentWorkTask.setCreateDate(new Date());
            currentWorkTask.setJobType(JobEnumType.NONE.getValue());
            currentWorkTask.setFlowNodeType(FlowNodeEnumType.END.getValue());
            currentWorkTask.setId(0);
            runtimeServiceDAO.save(currentWorkTask);

            //创建变量
            if (!ObjectUtil.isEmpty(variables))
            {
                String varNo = WorkFlowUtil.getVariableNo(currentWorkTask);
                runtimeServiceDAO.putWorkTaskVariable(varNo,new JSONObject(variables));
            }

            List<ConfFlowNode> nextNodeList = confWorkFlowDAO.getNextList(currentWorkTask.getFlowNo(), currentWorkTask.getNamespace(), currentWorkTask.getNodeId());
            for (ConfFlowNode node:nextNodeList)
            {
                WorkTask workTask = BeanUtil.copy(workTaskParam, WorkTask.class);
                workTask.setNodeId(node.getNodeId());
                workTask.setCreateDate(new Date());
                workTask.setUsers(workTaskParam.getUsers());
                //workTask.setFlowNodeType(FlowNodeEnumType.END.getValue());
                workTask.setId(0);
                runtimeServiceDAO.save(workTask);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ProcessResponse.error(e.getMessage());
        } finally {
            finishNode();
        }
        //流程发起人信息end
        return ProcessResponse.success(currentWorkTask);
    }
}
